/*
 * Created by Storm Zhang, Feb 11, 2014.
 */

package com.rio.volley;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import android.app.ActivityManager;
import android.content.Context;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.rio.core.Api;
import com.rio.core.L;
import com.rio.core.U;

public class RequestManager {
	
	private static RequestQueue mRequestQueue;
	
	private static ImageLoader mImageLoader;
	
	private static RequestManager mInstance;

	private RequestManager() {
		// no instances
	}
	
	public static RequestManager getInstance() {
		if(mInstance==null)
			mInstance = new RequestManager();
		return mInstance;
	}

	
	/**
	 * 初始化请求队列，是否配置图片下载器
	 * 
	 * @param context
	 */
	public void init(Context context, boolean needImageLoader) {
		mRequestQueue = Volley.newRequestQueue(context);
		if (needImageLoader) {
			int memClass = ((ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE))
					.getMemoryClass();
			// Use 1/8th of the available memory for this memory cache.
			int cacheSize = 1024 * 1024 * memClass / 8;
			mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(
					cacheSize));
		}
	}

	private static RequestQueue getRequestQueue() {
		if (mRequestQueue != null) {
			return mRequestQueue;
		} else {
			throw new IllegalStateException("RequestManager not initialized");
		}
	}

	public void addRequest(Request<?> request, Object tag) {
		if (tag != null) {
			request.setTag(tag);
		}
		getRequestQueue().add(request);
	}

	public static void cancelAll(Object tag) {
		getRequestQueue().cancelAll(tag);
	}

	/**
	 * Returns instance of ImageLoader initialized with {@see FakeImageCache}
	 * which effectively means that no memory caching is used. This is useful
	 * for images that you know that will be show only once.
	 * 
	 * @return
	 */
	public static ImageLoader getImageLoader() {
		if (mImageLoader != null) {
			return mImageLoader;
		} else {
			throw new IllegalStateException("ImageLoader not initialized");
		}
	}
	

}
